package com.txl.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.txl.domain.UserBean;
import com.txl.exception.DaoException;
import com.txl.utils.JdbcUtils;

public class UserDao {

	private QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
	
	//根据用户名和密码查找用户
	public UserBean find(String username, String password){
		try {
			String sql = "select * from users where username=? and password=?";
			Object params[] ={username, password};
			return (UserBean) runner.query(sql, params, new BeanHandler(UserBean.class));
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	//根据用户名查找用户
	public UserBean find(String username){
		try {
			String sql = "select * from users where username=?";
			return (UserBean) runner.query(sql, username, new BeanHandler(UserBean.class));
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	//添加用户
	public void add(UserBean user){
		try {
			String sql = "insert into users(username,password) values(?,?)";
			Object params[] ={user.getUsername(), user.getPassword()};
			runner.update(sql, params);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
	
	//更新用户
	public void update(UserBean user){
		try {
			String sql = "update users set password=? where username=?";
			Object params[] ={user.getPassword(),user.getUsername()};
			runner.update(sql, params);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
}
